// 全局状态机：地图多边形图层控制

import Vue from 'vue'

import VectorLayer from 'ol/layer/vector'
import VectorSource from 'ol/source/vector'
import GeoJSON from 'ol/format/GeoJSON'
// import point from './point'

// const getCenterOfExtent = function (Extent) {
//   var X = Extent[0] + (Extent[2] - Extent[0]) / 2
//   var Y = Extent[1] + (Extent[3] - Extent[1]) / 2
//   return [X, Y]
// }
// #####################
// #####################

// 初始状态
const state = {
  // 各多边形图层的配置
  layerOptions: {},
  // 各多边形图层的对象
  currentLayers: {}
}

// getters
const getters = {
  getLayerDetailTabsById: state => (layerGroupId, layerId) => {
    if (typeof layerGroupId === 'string' && typeof layerId === 'string') {
      return state.layerOptions[layerGroupId]['layers'][layerId]['detailTabs']
    }
  },
  getLayerOption: state => (layerGroupId, layerId) => {
    if (typeof layerGroupId === 'string' && typeof layerId === 'string') {
      return state.layerOptions[layerGroupId]['layers'][layerId]
    }
    if (typeof layerGroupId === 'string') {
      return state.layerOptions[layerGroupId]
    }
  },
  // 执行时返回函数，函数接受id作为参数
  getLayerArray: state => ({options = false, interaction = false} = {}) => {
    let layers = []
    for (let layerGroupId in state.currentLayers) {
      let optionsGroup = state.layerOptions[layerGroupId]['layers'] || []
      let noInteraction = state.layerOptions[layerGroupId].noInteraction
      let layerGroup = state.currentLayers[layerGroupId] || []
      let userOptions = options[layerGroupId] || []
      for (let layerId in layerGroup) {
        let layerOptions = optionsGroup[layerId] || {}
        // 传入参数需要交互图层且图层配置为非交互场合
        if (interaction && (noInteraction || layerOptions.noInteraction === true)) continue
        // 是需要的id或者为空
        if (userOptions.findIndex(obj => { return obj === layerId }) > -1 || !options) {
          layers.push(layerGroup[layerId])
        }
      }
    }
    return layers
  },
  // 执行时返回要生成选择框的数据
  getCheckboxArray: state => {
    let obj = {}
    for (let layerGroupId in state.layerOptions) {
      // 参数
      let {name, component, layers: layerOptions, isquery} = state.layerOptions[layerGroupId]
      let layers = state.currentLayers[layerGroupId]
      let items = []
      for (let layerId in layers) {
        items.push({'icon-svg': layerOptions[layerId]['icon-svg'], name: layerOptions[layerId]['name'], id: layerId, layerGroupId, checked: layers[layerId].getVisible()})
      }
      obj[layerGroupId] = {items, name, component, isquery}
    }
    return obj
  },
  // 执行时返回函数，函数接受id作为参数
  getTabArray: state => {
    let tabArray = []
    for (let layerGroupId in state.currentLayers) {
      let optionsGroup = state.layerOptions[layerGroupId]['layers'] || []
      let noInteraction = state.layerOptions[layerGroupId].noInteraction
      let layerGroup = state.currentLayers[layerGroupId] || []
      for (let layerId in layerGroup) {
        let layerOptions = optionsGroup[layerId]
        let layer = layerGroup[layerId]
        // 是无交互图层组或无交互图层跳过
        if (noInteraction === true || layerOptions.noInteraction === true || !layer.getVisible()) continue
        tabArray.push({
          // 名称
          name: layerOptions.name || layerId,
          // 组id
          layerGroupId,
          // id
          id: layerId,
          // 数据来源
          src: layerOptions.src,
          // 表格数据来源
          tableSrc: layerOptions.tableSrc,
          // 表格查询数据来源
          tableQuerySrc: layerOptions.tableQuerySrc,
          // 表哥结构
          tableFormat: layerOptions.tableFormat
        })
      }
    }
    return tabArray
  }
}

// 异步操作
const actions = {
  // 创建指定多边形图层
  createPolygonLayers: function ({ commit, state }, layerOptions) {
    // 保存原始配置备用
    state.layerOptions = layerOptions
    // 遍历传入配置
    for (var layerGroupId in layerOptions) {
      // 取出一个
      let option = layerOptions[layerGroupId]
      const {layers} = option
      for (let layerId in layers) {
        let layerOption = layers[layerId]
        // 设定数据源
        let vectorSource = new VectorSource({
          // 解析器
          format: new GeoJSON(),
          loader: function (extent, resolution, projection) {
            const {$getText, $handleSrc} = Vue.prototype._vue
            let {url, param} = $handleSrc(layerOption.src)
            $getText(url, param).then(data => {
              // console.log(data)
              let f = vectorSource.getFormat()
              // 解析器解析GeoJSON报文
              let features = f.readFeatures(data, {featureProjection: projection})
              // 获取回调函数
              let triggeCallback = layerOption.triggeCallback
              // 因执行顺序问题,需要获取isshow的反向状态
              let show = !layerOption.isShow
              // 调用回调函数
              triggeCallback('layer-visible-change', show, features)
              f.readProjection(data)
              f.getLastExtent()
              vectorSource.addFeatures(features)
            }).catch(e => {
              vectorSource.removeLoadedExtent(extent)
            })
          }
        })
        // 创建描点图层
        let layer = new VectorLayer({
          // 设定数据源
          source: vectorSource,
          // 样式
          style: layerOption.featureStyle
        })
        layer.set('__triggeCallback', layerOption.triggeCallback, false)
        layer.set('__id', layerId, false)
        layer.set('__layerGroupId', layerGroupId, false)
        layer.set('__featureStyle', layerOption.featureStyle, false)
        layer.set('__featureStyle_H', layerOption.featureStyle_H, false)
        // 设定是否为隐藏
        layer.setVisible(layerOption.isShow)
        // 图层级别默认为3
        layer.setZIndex(layerOption['z-index'] || 3)
        // 提交修改数据
        commit('addPolygonLayer', {layerGroupId, layerId, layer})
      }
    }
  },
  // 显示指定图层
  changeMapPolygonLayersShow: function ({ commit, state }, option) {
    // 提交修改数据
    commit('changeMapPolygonLayerShow', option)
  },
  // 显示指定焦点
  highlightSelectFeature ({state, dispatch}, {featureIDKey, featureIDValue, layerID, layerGroupId}) {
    let layer = state.currentLayers[layerGroupId][layerID]
    let src = layer.getSource()
    src.forEachFeature(function (feature) {
      let value = ''
      if (feature.get(featureIDKey)) {
        value = feature.get(featureIDKey)
      } else {
        value = feature.get('stcd')
      }

      if (value === featureIDValue) {
        // feature.setStyle(state.tracingPointOptions[layerID].featureStyle_H)
        // 保存选中状态的额样式
        feature.set('__id', layerID, false)
        // 保存选中状态的额样式
        feature.set('__featureStyle_H', state.layerOptions[layerGroupId]['layers'][layerID].featureStyle_H, false)
        // 保存选中状态的额样式
        feature.set('__featureStyle', state.layerOptions[layerGroupId]['layers'][layerID].featureStyle, false)
        // 激活气泡
        dispatch('popup', {feature, selectCallback: function () {}})
      }
    })
  }
}

// 提交操作
const mutations = {
  // 改变描点图层的显示状态
  changeMapPolygonLayerShow: function (state, { group, isShow }) {
    for (let groupId in group) {
      let layerIds = group[groupId] || []
      // 遍历id
      layerIds.forEach(layerId => {
        // 复制一个描点层对象
        let tracingPolygonLayer = state.currentLayers[groupId][layerId]
        // 修改显示，这里由openlayers的封装监听数据的修改
        tracingPolygonLayer.setVisible(isShow)
        let groupObj = state.currentLayers[groupId]
        groupObj[layerId] = tracingPolygonLayer
        // 使用Vue.set修改数据通知vue刷新界面
        Vue.set(state.currentLayers, groupId, groupObj)
        // 获取图层用户自定义回调
        let triggeCallback = tracingPolygonLayer.get('__triggeCallback')
        // 是函数

        if (typeof triggeCallback === 'function') {
          // 执行: 触发图层可见状态变化事
          triggeCallback('layer-visible-change', isShow, tracingPolygonLayer.getSource().getFeatures())
        }
      })
    }
  },
  changeLayersOption (state, {group, layer, option}) {
    // 设定属性
    Vue.set(
      // 全部描点层对象
      state.layerOptions[group]['layers'],
      // id
      layer,
      // 创建描点图层
      option
    )
    state.currentLayers[group][layer].set('__triggeCallback', option['triggeCallback'])
  },
  // 创建图层
  addPolygonLayer: function (state, {layerGroupId, layerId, layer}) {
    if (typeof state.currentLayers[layerGroupId] === 'undefined') {
      // 设定属性
      Vue.set(
        // 全部描点层对象
        state.currentLayers,
        // id
        layerGroupId,
        // 创建描点图层
        {}
      )
    }
    // 设定属性
    Vue.set(
      // 全部描点层对象
      state.currentLayers[layerGroupId],
      // id
      layerId,
      // 创建描点图层
      layer
    )
  },
  // 隐藏所有
  hideAllLayers (state) {
    // for (let groupId in group) {
    //   let layerIds = group[groupId] || []
    //   // 遍历id
    //   layerIds.forEach(layerId => {
    //     // 复制一个描点层对象
    //     let tracingPolygonLayer = state.currentLayers[groupId][layerId]
    //     // 修改显示，这里由openlayers的封装监听数据的修改
    //     tracingPolygonLayer.setVisible(isShow)
    let layerGroup = state.currentLayers
    for (let layerGroupKey in layerGroup) {
      let layers = layerGroup[layerGroupKey] || {}
      for (let layerKey in layers) {
        layers[layerKey].setVisible(false)
      }
      // layerNames.forEach(layerName => {
      //   let tracingPolygonLayer = state.currentLayers[layer][layerName]
      //   tracingPolygonLayer.setVisible(false)
      // })
    }
  }
  // 在监听加载的时候调用 this.$store.commit('hideAllLayers',false)
}
// 导出
export default {
  state,
  getters,
  actions,
  mutations
}
